import { Component } from '@angular/core';
import { IonicPage, NavController, ViewController, ToastController, ModalController, Platform, NavParams, } from 'ionic-angular';
import { HttpProvider } from '../../providers/http/http';
import { StorageProvider } from '../../providers/storage/storage';
import { DialogProvider } from '../../providers/dialog/dialog';
import { Md5 } from "ts-md5/dist/md5";
import { UserInfoProvider } from '../../providers/user-info/user-info';
import { UserDataService } from '../../providers/service/user-data.service';
import { OrderDataService } from '../../providers/service/order-data.service';
import { Network } from '@ionic-native/network';
import { Login2Page } from './dio/login2';
import { AppVersion } from '@ionic-native/app-version';
import { LoadingController, Loading } from 'ionic-angular';
/**
 * Generated class for the LoginPage page.
 *
 * See https://ionicframework.com/docs/components/#navigation for more info on
 * Ionic pages and navigation.
 */

@IonicPage()
@Component({
	selector: 'page-login',
	templateUrl: 'login.html',
})
export class LoginPage {
	/*模型设置*/
	public loginInfo = {
		UserName: '',
		PassWord: '',
		isAutomaticLogon: false
	};

	version = '1.0.0';
	sendStatus = 0;

	a: number;
	// 登录信息
	userInfo: user_info = new user_info();

	// 定位用
	options = {
		enableHighAccuracy: true,  // 是否使用 GPS
		maximumAge: 30000,         // 缓存时间
		timeout: 27000,            // 超时时间
		coorType: 'bd09ll'         // 默认是 gcj02，可填 bd09ll 以获取百度经纬度用于访问百度 API
	  }

	constructor(
		public navCtrl: NavController,
		public viewCtrl: ViewController,
		public http: HttpProvider,
		public storage: StorageProvider,
		public dialog: DialogProvider,
		public toastCtrl: ToastController,
		public user: UserInfoProvider,
		public order: OrderDataService,
		public userData: UserDataService,
		private network: Network,
		public modalCtrl: ModalController,
		private appVersion: AppVersion,
		public loadingCtrl: LoadingController
	) { }

	async openModal(characterNum) {
		// this.navCtrl.push('Login2Page');
		// let modal = this.modalCtrl.create('Login2Page', { characterNum: 1111 });
		// modal.onDidDismiss(data => {
		// 	console.log(data);
		// });
		// modal.present();
		this.toastCtrl.create({
			message: this.network.type,
			duration: 2000,
			position: 'top'
		}).present();
	}

	async ionViewDidLoad() {
		console.log('ionViewDidLoad LoginPage');
		let a = await this.userData.find((user) => user.key !== '');
		
		if (a.length > 0) {
			this.loginInfo.UserName = a[0]['phone'];
			this.loginInfo.PassWord = a[0]['password'];
			this.loginInfo.isAutomaticLogon = a[0]['isAutomaticLogon'];
			this.userInfo = a[0];
		}

		// this.getPoint();
		//&& help.uploud ==0
	}

	// 页面跳转的方式
	register() {
		this.sendStatus++;
		this.navCtrl.push('RegisterPage',{
			sendStatus : this.sendStatus
		});
	}

	forgetpwd() {
		this.sendStatus++;
		this.navCtrl.push('ForgetPwdPage',{
			sendStatus : this.sendStatus
		});
	}


	/**
	 * 用户登录
	 */
	async loginOnSuccess() {
		// if (this.network.type === 'none') {
		// 	this.navCtrl.push('TabsPage');
		// 	let a = await this.userData.find((user) => user.key !== '')
		// 	this.userInfo = a[0];
		// 	this.user.setuserInfo(this.userInfo);
		// 	return;
		// }
		var subscriber = /^((13[0-9])|(14[5,7,9])|(15[^4])|(18[0-9])|(17[0,1,3,5,6,7,8]))\d{8}$/;
		var silly = subscriber.test(this.loginInfo.UserName);
		if (this.loginInfo.UserName == '' || this.loginInfo.UserName == null) {
			// this.dialog.showAlert('警告','请输入手机号码');
			this.toastCtrl.create({
				message: '请输入手机号码',
				duration: 2000,
				position: 'top'
			}).present();
			return;
		}
		if (this.loginInfo.UserName.length != 11) {
			// this.dialog.showAlert('警告', '请输入11位手机号码');
			this.toastCtrl.create({
				message: '请输入11位手机号码',
				duration: 2000,
				position: 'top'
			}).present();
			return;
		}
		if (!silly) {
			// this.dialog.showAlert('警告', '手机号不合法');
			this.toastCtrl.create({
				message: '手机号不合法',
				duration: 2000,
				position: 'top'
			}).present();
			return;
		}
		if (this.loginInfo.PassWord == '' || this.loginInfo.PassWord == null) {
			// this.dialog.showAlert('警告', '请输入密码');
			this.toastCtrl.create({
				message: '请输入密码',
				duration: 2000,
				position: 'top'
			}).present();
			return;
		}
		// else if(this.loginInfo.PassWord.length!=6){
		// 	this.dialog.showAlert('警告','密码只能6位');
		// 	return;
		// }
		/*把表单的空值传到定义的属性名*/
		var params = {
			username: this.loginInfo.UserName,
			password: this.loginInfo.PassWord,
			isAutomaticLogon: true,
		};
		let loading = this.loadingCtrl.create({
	      	content: '登录中...'
	  	});
		loading.present();
		/*调用接口的方式,这种写法接受参数需要json的格式*/
		if (this.network.type === 'none' || this.network.type === '2g') {
			let a = await this.userData.find((b) => b.key !== '');
			if (a.length === 0) {
				this.dialog.showToast('提示', '登录失败请重试');
				loading.dismiss();
				return;
			}
			if (a[0].password === params.password && a[0].phone === params.username) {
				this.user.setuserInfo(this.userInfo);
				loading.dismiss();
				this.navCtrl.push('TabsPage');
			} else { 
				loading.dismiss();
				this.dialog.showToast('提示', '当前无网络只能登陆上一次登陆的用户'); 
			}

			return;
		}
		await this.http.postJson('', 'users/member/login', { 'phone': params.username, 'password': params.password }, '')
			.then(res => {
				loading.dismiss();
				console.log(res);
				if (res['status'] == 200) {
					//this.dialog.showAlert('您好'+res['data']['nickname'], res['message']);		
					this.http.login_stuta = 1;
					res['data']['password'] = params.password;
					res['data']['isAutomaticLogon'] = params.isAutomaticLogon;
					// this.storage.saveStorage("login_info", res['data']);
					this.userInfo = res['data'];
					this.user.setuserInfo(this.userInfo);
					this.http.setAuthorization(res['data']['access_token']);//该令牌唯一表示该用户、用户的组和用户的特权。系统使用令牌控制用户可以访问哪些安全对象，并控制用户执行相关系统操作的能力
					this.getdictionary();
					this.navCtrl.push('TabsPage');
				} else {
					this.toastCtrl.create({
						message: res['message'],
						duration: 2000,
						position: 'top'
					}).present();
				}
			});
	}

	getdictionary() {
		this.http.postJson('', 'aindex/dictionary/index',
			{
				select: "m.D_GROUP",
				joinWith: "group", "groupby": "D_GROUP", "indexBy": "D_GROUP", "limit": 0,
				where: ["<>", "s_dictionary.D_STATE", 0]
			}, '')
			.then(res => {
				if (res['status'] == 200) {
					this.storage.saveStorage("dictionary", JSON.stringify(res['data']));
				}
			});
	}

	eliminate(UserName) {
		this.loginInfo.PassWord = '';
	}

	// getPoint() {
	// 	let options = {
	// 		enableHighAccuracy: true,  // 是否使用 GPS
	// 		maximumAge: 30000,         // 缓存时间
	// 		timeout: 27000,            // 超时时间
	// 		coorType: 'bd09ll'         // 默认是 gcj02，可填 bd09ll 以获取百度经纬度用于访问百度 API
	// 	  }

	// 	navigator.geolocation.getCurrentPosition((success) => {	}, (error) => { 
	// 		// this.dialog.showConfirm('拒绝使用定位会造成充电桩无法搜索，是否重新开启定位？', '').then(success => {
	// 		// 	this.getPoint();
	// 		//   },
	// 		//   fail => {
  
	// 		//   })
	// 	 }, options);	
	//   }

}


export class user_info {
	member_id: any;
	nickname: any;
	phone: any;
	balance: any;
	local_balance: any;
	member_state: any;
	created_at: any;
	updated_at: any;
	cuser_id: any;
	uuser_id: any;
	is_del: any;
	password: any;
	file_type_id: any;
	access_token: any;
	isAutomaticLogon: any;
}